/* fac.c */
/*

gcc -o fac -I/usr/lib/erlang/lib/erl_interface-3.6.4/include -L/usr/lib/erlang/lib/erl_interface-3.6.4/lib fac.c -lerl_interface -lei -lpthread

*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include "erl_interface.h"
#include "ei.h"

#define BUFSIZE 100

#define MAP_WIDTH 3
#define MAP_HEIGHT 3

int main(int argc, char **argv)
{
	int fd;
	int loop = 1;
	int got;
	unsigned char buf[BUFSIZE];
	ErlMessage emsg;
	ETERM *msg_sender_p, *msg_tuple_p, *msg_type_p, *cell_x_p, *cell_y_p, *cell_trawa_p;
	int cell_x, cell_y;
	double cell_trawa, mapa[MAP_WIDTH][MAP_HEIGHT];

	struct in_addr adres;

	erl_init(NULL, 0);

	if (erl_connect_init(1, "my", 0) == -1)
		erl_err_quit("erl_connect_init error");

	//inet_aton("10.22.114.200", &adres);
	//if ((fd = erl_xconnect(&adres, "blah")) < 0)
	if ((fd = erl_connect("blah@hopsiup")) < 0)
		erl_err_quit("erl_connect error");

  printf("połączony\n");
while (1) {
  ETERM *command = erl_format("af"); // eg. "{ok, 1234}"
	erl_reg_send(fd, "fac", command);
	erl_free_term(command);
  printf("wiadomość wysłana\n");

	got = erl_receive_msg(fd, buf, BUFSIZE, &emsg);
  printf("wiadomość odebrana\n");
	if (got == ERL_TICK)
	{
		/* ignore */
	  printf("tick\n");
	}
	else if (got == ERL_ERROR)
	{
		loop = 0;
	  printf("error\n");
	}
	else
	{
		if (emsg.type == ERL_REG_SEND)
		{
			msg_sender_p = erl_element(1, emsg.msg);
			msg_tuple_p = erl_element(2, emsg.msg);
			msg_type_p = erl_element(1, msg_tuple_p);
			switch (ERL_INT_VALUE(msg_type_p))
			{
				case 1: /* trawa */
					cell_x_p = erl_element(2, msg_tuple_p);
					cell_y_p = erl_element(3, msg_tuple_p);
					cell_trawa_p = erl_element(4, msg_tuple_p);
					cell_x = ERL_INT_VALUE(cell_x_p);
					cell_y = ERL_INT_VALUE(cell_y_p);
					cell_trawa = ERL_FLOAT_VALUE(cell_trawa_p);
					mapa[cell_x][cell_y] = cell_trawa;
					printf("trawa(%d,%d) = %lf\n", cell_x, cell_y, cell_trawa);
					erl_free_term(cell_x_p);
					erl_free_term(cell_y_p);
					erl_free_term(cell_trawa_p);
				break;
			}
			erl_free_term(emsg.from);
			erl_free_term(emsg.msg);
			erl_free_term(msg_sender_p);
			erl_free_term(msg_tuple_p);
			erl_free_term(msg_type_p);
		}
	}
}
}
